package com.example.woke;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bumptech.glide.Glide;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.netease.nim.uikit.GlideApp;
import com.woke.method.Md5jarss;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.wokeMy.view.model.Constant;
import com.wokeMy.view.util.Util;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

import cn.jpush.android.api.JPushInterface;

public class PswchangeActivity extends Activity {

	private EditText mEold, mEnew, mEnewa,editimageCode;
	private TextView mTok;
	private int intExtra;
	private String paypsw;
	private MyApp application;
	private RelativeLayout mBar;
	private RelativeLayout mRepaysw;
	private EditText mEphone;
	private TextView mTgetcode;
	private int jtime = 60;
	private Runnable runnableRef = new Runnable () {
		public void run() {

			if (jtime == 0) {
				Message msg = new Message ();
				msg.what = 911;
				mHandler.sendMessage (msg);
				mHandler.removeCallbacks (runnableRef);
			} else {
				jtime = jtime - 1;
				Message msg = new Message ();
				msg.what = 109;
				mHandler.sendMessage (msg);
			}

			mHandler.postDelayed (runnableRef, 1000);
		}
	};
	Handler mHandler = new Handler () {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage (msg);
			if (msg.what == 911) {
				mTgetcode.setText ("点击发送验证码");
				mHandler.removeCallbacks (runnableRef);
				jtime = 60;
				mTgetcode.setClickable (true);
				mTgetcode.setBackgroundResource (R.drawable.rect_lightred);
			} else if (msg.what == 109) {
				mTgetcode.setText ("(" + jtime + ")秒后重新发送");
				mTgetcode.setBackgroundResource (R.drawable.rect_lightgray);
				mTgetcode.setClickable (false);
			} else if (msg.what == 1) {
//				mBar.startAnimation(
//						AnimationUtils.loadAnimation(RegisterActivity.this, R.anim.btn_rotate));
				mBar.setVisibility (View.VISIBLE);
			} else if (msg.what == 2) {
//				mBar.clearAnimation();
				mBar.setVisibility (View.GONE);
			}
		}
	};
	String registrationID;
	Dialog mydialog;
	private AlertView mAlertView;
	ImageView imageCode;
	long lastClick = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView (R.layout.activity_pswchange);
		registrationID = JPushInterface.getRegistrationID(PswchangeActivity.this);
		Intent intent = getIntent ();
		intExtra = intent.getIntExtra ("name", 0);//0 支付密码 1用户密码
		application = (MyApp) getApplication ();
		if (application.getDatas_load () != null) {
			paypsw = application.getDatas_load ().getPay_pwd ();
		}
		intview ();
		imageYzm();
	}

	private void intview() {
		findViewById (R.id.avpsw_image_back).setOnClickListener (new OnClickListener () {
			@Override
			public void onClick(View v) {
				finish ();
			}
		});
		mBar = (RelativeLayout) findViewById (R.id.avpsw_progre_bar);
		mRepaysw = (RelativeLayout) findViewById (R.id.avpsw_relative_paypsw);
		mEphone = (EditText) findViewById (R.id.avpsw_edit_phonecode);//�޸�֧������ʱҪ��ȡ�ֻ���֤��
		mTgetcode = (TextView) findViewById (R.id.avpsw_text_getcode);//��ȡ��֤��
		mTgetcode.setOnClickListener (new OnClickListener () {

			@Override
			public void onClick(View v) {
				if (application.getDatas_load () == null) return;
				String imageCode = editimageCode.getText().toString().trim();
				if(TextUtils.isEmpty(imageCode)){
					Toast.makeText(PswchangeActivity.this, "请输入图形验证码！", Toast.LENGTH_SHORT).show();
				}else {
					if (!fastClick()){
						mydialog=Util.createLoadingDialog(PswchangeActivity.this);
						yzm(application.getDatas_load ().getUser_login (),imageCode);
					}
				}
//				getdatacode (application.getDatas_load ().getUser_login ());
//				mTgetcode.setClickable (false);
			}
		});
		TextView mTtielt = (TextView) findViewById (R.id.avpsw_text_title);
		TextView mTatten = (TextView) findViewById (R.id.avpsw_text_attention);
		mEnew = (EditText) findViewById (R.id.avpsw_edit_new);
		mEnewa = (EditText) findViewById (R.id.avpsw_edit_newagain);
		imageCode = (ImageView) findViewById (R.id.pay_image_code);
		imageCode.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!fastClick()){
					imageYzm();
				}
			}
		});
		editimageCode = (EditText) findViewById (R.id.pay_edit_img);
		if (intExtra == 0) {
			mTtielt.setText ("修改支付密码");
			mTatten.setText ("支付密码为0-9任意6位数");
			int inputType = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD;
			mEnew.setInputType (inputType);
			mEnewa.setInputType (inputType);
			mEnew.setFilters (new InputFilter[]{new InputFilter.LengthFilter (6)});
			mEnewa.setFilters (new InputFilter[]{new InputFilter.LengthFilter (6)});
		} else {
			mTtielt.setText ("修改账户密码");
			mTatten.setText ("账户密码为6-20位字母或数字");
			mRepaysw.setVisibility (View.GONE);
		}
		mEold = (EditText) findViewById (R.id.avpsw_edit_old);
		if (intExtra == 0) {
			mEold.setVisibility (View.GONE);
		}
		mTok = (TextView) findViewById (R.id.avpsw_text_ok);
		mTok.setOnClickListener (new OnClickListener () {
			@Override
			public void onClick(View v) {

				if (intExtra == 0) {
					String authcode = mEphone.getText ().toString ().trim ();
					String newm = mEnew.getText ().toString ().trim ();
					String newa = mEnewa.getText ().toString ().trim ();
					if (TextUtils.isEmpty (authcode)) {
						Toast.makeText (PswchangeActivity.this, "短信验证码不能为空！", Toast.LENGTH_SHORT)
								.show ();
					} else if (TextUtils.isEmpty (newm)) {
						Toast.makeText (PswchangeActivity.this, "新密码不能为空！", Toast.LENGTH_SHORT)
								.show ();
					} else if (TextUtils.isEmpty (newa)) {
						Toast.makeText (PswchangeActivity.this, "确认密码不能为空！", Toast.LENGTH_SHORT)
								.show ();
					} else if (! newm.equals (newa)) {
						Toast.makeText (PswchangeActivity.this, "两次密码输入不一致！", Toast.LENGTH_SHORT)
								.show ();
					} else {
						gettextandsend ("", newm, authcode);
					}
				} else {
					String oldPwd = mEold.getText ().toString ().trim ();
					String newm = mEnew.getText ().toString ().trim ();
					String newa = mEnewa.getText ().toString ().trim ();
					if (TextUtils.isEmpty (oldPwd)) {
						Toast.makeText (PswchangeActivity.this, "原始密码不能为空！", Toast.LENGTH_SHORT)
								.show ();
					} else if (TextUtils.isEmpty (newm)) {
						Toast.makeText (PswchangeActivity.this, "新密码不能为空！", Toast.LENGTH_SHORT)
								.show ();
					} else if (TextUtils.isEmpty (newa)) {
						Toast.makeText (PswchangeActivity.this, "确认密码不能为空！", Toast.LENGTH_SHORT)
								.show ();
					} else if (! newm.equals (newa)) {
						Toast.makeText (PswchangeActivity.this, "两次密码输入不一致！", Toast.LENGTH_SHORT)
								.show ();
					} else {
						gettextandsend (oldPwd, newm, "");
					}
				}


			}
		});
	}

	private void getdatacode(String phone) {
		AsyncHttpClient ahc = new AsyncHttpClient ();
		PersistentCookieStore myCookieStore = new PersistentCookieStore (PswchangeActivity.this);
		ahc.setCookieStore (myCookieStore);
		RequestParams params = new RequestParams ();
		params.put ("g", "api");
		params.put ("m", "Public");
		params.put ("a", "sendCode");
		params.put ("username", phone);
		ahc.get (HttpMethods.BASEURL, params, new JsonHttpResponseHandler () {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess (statusCode, headers, response);
				Log.e ("response", "response" + response);
				try {
					String flag = response.getString ("flag");
					if (flag.equals ("success")) {
						Toast.makeText (PswchangeActivity.this, "验证码已发送！", Toast.LENGTH_SHORT)
								.show ();
						Thread thread = new Thread (runnableRef);
						thread.start ();
					}
				} catch (JSONException e) {
					e.printStackTrace ();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure (statusCode, headers, responseString, throwable);
				Log.e ("response", "失败" + responseString);
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart ();
				mBar.setVisibility (View.VISIBLE);
//				Message msg = new Message();
//        		msg.what = 1;//��������
//        		mHandler.sendMessage(msg);
			}

			@Override
			public void onFinish() {
				super.onFinish ();
				mTgetcode.setClickable (true);
				mBar.setVisibility (View.GONE);
//				Message msg = new Message();
//        		msg.what = 2;//�رն���
//        		mHandler.sendMessage(msg);
			}
		});
	}

	private void gettextandsend(String old, final String newm, String trim) {
		if (application.getDatas_load () == null) return;
		try {
			int userId = Integer.parseInt (application.getDatas_load ().getId ());
			if (userId <= 0) return;
		} catch (Exception e) {
			return;
		}
		Log.e ("Pswchange", "用户id==" + application.getDatas_load ().getId ());
		AsyncHttpClient ahc = new AsyncHttpClient ();
		PersistentCookieStore myCookieStore = new PersistentCookieStore (PswchangeActivity.this);
		ahc.setCookieStore (myCookieStore);
		RequestParams params = new RequestParams ();
		params.put ("g", "api");
		params.put ("m", "user");
		if (intExtra == 0) {
			params.put ("a", "updataPaypw");
			params.put ("user_id", application.getDatas_load ().getId ());
			params.put ("pay_pwd", newm);

			params.put ("phone", application.getDatas_load ().getUser_login ());
			params.put ("code", trim);

		} else {
			params.put ("a", "updatapw");
			params.put ("user_id", application.getDatas_load ().getId ());
			params.put ("user_pass", newm);
			params.put ("user_oldpass", old);
		}
		Log.e ("修改密码params", params.toString ());

		ahc.get (HttpMethods.BASEURL, params, new JsonHttpResponseHandler () {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess (statusCode, headers, response);
//
				Log.e ("修改密码response", response.toString ());
				try {
					String flag = response.getString ("flag");
					String info = response.getString ("info");
					if (flag.equals ("success")) {
						Toast.makeText (PswchangeActivity.this, "修改成功！", Toast.LENGTH_SHORT)
								.show ();
						String get32md5 = Md5jarss.get32MD5 ("sp_");
						String get32md52 = Md5jarss.get32MD5 (newm);
						String sp1 = get32md5.substring (0, 12);
						String sp11 = get32md5.substring (get32md5.length () - 4, get32md5.length ());

//						Log.e("sp��"+get32md5, "֧���ܴa"+get32md52);
						String pswold = sp1 + get32md52 + sp11;
						if (application.getDatas_load () != null) {
							Datas_load datas_load = application.getDatas_load ();
							datas_load.setPay_pwd (pswold);
						}
						finish ();
					} else {
						mAlertView=new AlertView("提示",info, null, new String[]{"确定"}, null, PswchangeActivity.this, AlertView.Style.Alert,null);
						mAlertView.show();
					}
				} catch (JSONException e) {
					e.printStackTrace ();
				}
			}

			@Override
			public void onStart() {
				super.onStart ();
				mBar.setVisibility (View.VISIBLE);
				mTok.setBackgroundResource (R.drawable.rect_lightgray);
				mTok.setClickable (false);
			}

			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
				super.onFinish ();
				mBar.setVisibility (View.GONE);
				mTok.setBackgroundResource (R.drawable.rect_lightred);
				mTok.setClickable (true);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure (statusCode, headers, responseString, throwable);
				Log.e ("responseString", "responseString" + responseString);
				Toast.makeText (PswchangeActivity.this, "修改失败！", Toast.LENGTH_SHORT).show ();
			}
		});
	}
	//图形验证码 请求 （防短信轰炸）
	private void imageYzm() {
		registrationID=String.valueOf(System.currentTimeMillis());
		String url=Constant.IMAGEYZM+registrationID;
		Log.e("imageYzm",url);
		GlideApp.with(this)
				.load(url)
				.placeholder(R.mipmap.icn__launch_oem)
				.error(R.mipmap.icn__launch_oem)
				.into(imageCode);
	}
	//图形验证码后短信验证码
	private void yzm(String mobile,String imcode) {
		AsyncHttpClient ahc = new AsyncHttpClient();
		RequestParams params = new RequestParams();
		params.put("mobile",mobile);
		params.put("code",imcode);
		params.put("token",registrationID);
		Log.e("图形验证码后短信验证码arams",params.toString());
		//url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
		ahc.post(Constant.DXYZM, params, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int i, Header[] headers, byte[] bytes) {
				Util.closeDialog(mydialog);
				//判断状态码
				if(i == 200){
					//获取结果
					try {
						String result = new String(bytes, "utf-8");
						//                        Toast.makeText(CreditRepayActivity.this, result, Toast.LENGTH_SHORT).show();
						Log.e("图形验证码后短信验证码Result", result);
						try {
							JSONObject jsonObject = new JSONObject(result);
							String flag = jsonObject.getString("flag");
							if(flag.equals("success")){
								Toast.makeText(PswchangeActivity.this, "验证码已发送！", Toast.LENGTH_SHORT).show();
								Thread thread = new Thread(runnableRef);
								thread.start();
							}else {
								mAlertView=new AlertView("提示",jsonObject.getJSONObject("data").getString("data"), null, new String[]{"确定"}, null, PswchangeActivity.this, AlertView.Style.Alert,null);
								mAlertView.show();

							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
				Util.closeDialog(mydialog);
			}
		});
	}
	public boolean fastClick() {
		if (System.currentTimeMillis() - lastClick < 1000) {
			Toast.makeText(PswchangeActivity.this,"不要点击过快！",Toast.LENGTH_SHORT).show();
			return true;
		}
		lastClick = System.currentTimeMillis();
		return false;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (mAlertView != null && mAlertView.isShowing()) {
				mAlertView.dismiss();
				return false;
			}
		}
		return super.onKeyDown(keyCode, event);

	}
}
